import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';
import { Product } from 'src/entities/product.entity';
import { ProductOption } from 'src/entities/product-option.entity';
import { DataSource, Repository } from 'typeorm';
import { Category } from 'src/entities/category.entity';
import { ProductQueryDto } from './dto/product-query.dto';

@Injectable()
export class ProductService {
  
  constructor(

    @InjectRepository(Product)
    private productsRepository: Repository<Product>,

    @InjectRepository(ProductOption)
    private productOptionsRepository: Repository<ProductOption>,

    @InjectRepository(Category)
    private categoryRepository: Repository<Category>,
    
  ) {}

  async create(createProductDto: CreateProductDto) {
    const { productOptionList, categoryId, ...productData } = createProductDto

    try {
      const insertResult = await this.productsRepository
      .createQueryBuilder()
      .insert()
      .into(Product)
      .values(productData)
      .execute()

      const productId = insertResult.identifiers[0].skuId;

      if (productOptionList && productOptionList.length > 0) {
        await this.productOptionsRepository
          .createQueryBuilder()
          .insert()
          .into(ProductOption)
          .values(
            productOptionList.map(item => ({
              ...item,
              product: productId
            }))
          )
          .execute()
      }

      await this.categoryRepository
        .createQueryBuilder()
        .relation(Product, 'category')
        .of(productId)
        .set(categoryId)

    } catch(err) {
      console.log('新增商品报错： ', err)
    }
   
  }

  async findAll(productQueryDto: ProductQueryDto) {

    const { productName, categoryId, page, pageSize } = productQueryDto

    const queryBuilder = this.productsRepository.createQueryBuilder('product')
      .leftJoinAndSelect('product.ProductOptionList', 'productOption')
      .leftJoinAndSelect('product.category', 'category')

    if (productName) {
      queryBuilder.andWhere('product.productName LIKE :productName', { productName })
    }

    if (categoryId) {
      queryBuilder.andWhere('category.categoryId :categoryId', { categoryId })
    }

    queryBuilder.skip((page - 1) * pageSize)
      .take(pageSize)

    queryBuilder.orderBy('product.productName', 'ASC')

    const [products, total] = await queryBuilder.getManyAndCount()

    return [products, total]

  }

  findOne(id: number) {
    return `This action returns a #${id} product`;
  }

  async update(updateProductDto: UpdateProductDto) {
    const { productOptionList, categoryId, ...productData } = updateProductDto;

    const res = await this.productsRepository.createQueryBuilder('product')
      .update(Product)
      .set(productData)
      .where('product.skuId = :skuId', { skuId: productData.skuId })
      .execute()

    // 更新关联 productOptionList，categoryId
  }

  async remove(skuId: string) {
    
    const builder =  this.productsRepository.createQueryBuilder()

    const res = await builder.delete()
      .from(Product)
      .where('skuId = :skuId', { skuId })
      .execute()

    return res
  }

}
